package com.guaji.system.gaodemap


import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.amap.api.location.AMapLocation
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.location.AMapLocationListener
import com.amap.api.maps2d.AMap
import com.amap.api.maps2d.CameraUpdateFactory
import com.amap.api.maps2d.MapView
import com.amap.api.maps2d.model.LatLng
import com.amap.api.maps2d.model.MarkerOptions
import com.amap.api.maps2d.model.MyLocationStyle
import com.guaji.system.R
import com.guaji.system.R.*

class MapMainActivity : AppCompatActivity(), AMapLocationListener {
    // 地图控件
    private lateinit var mMapView: MapView
    // 地图对象
    private lateinit var aMap: AMap
    // 定位客户端
    private var mLocationClient: AMapLocationClient? = null
    // 定位参数
    private var mLocationOption: AMapLocationClientOption? = null
    // "我的位置"显示样式
    private lateinit var myLocationStyle: MyLocationStyle

    // 所需权限
    private val REQUEST_PERMISSIONS = arrayOf(
        Manifest.permission.ACCESS_FINE_LOCATION,
        Manifest.permission.ACCESS_COARSE_LOCATION,
        Manifest.permission.INTERNET
    )
    private val PERMISSION_REQUEST_CODE = 100

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(layout.activity_map_main)  // 设置布局文件

        // 初始化地图控件
        mMapView = findViewById(R.id.mapView)
        mMapView.onCreate(savedInstanceState)  // 必须调用的生命周期方法

        // 检查权限
        checkPermissions()
    }

    // 检查并请求权限
    private fun checkPermissions() {
        val needRequest = REQUEST_PERMISSIONS.filter {
            ContextCompat.checkSelfPermission(this, it) != PackageManager.PERMISSION_GRANTED
        }.toTypedArray()

        if (needRequest.isNotEmpty()) {
            ActivityCompat.requestPermissions(this, needRequest, PERMISSION_REQUEST_CODE)
        } else {
            // 权限已获取，更新隐私合规并初始化地图和定位
            updatePrivacyCompliance()
        }
    }

    // 显示隐私政策弹窗
    private fun showPrivacyPolicyDialog() {
        val builder = AlertDialog.Builder(this)
        builder.setTitle("隐私政策")
        builder.setMessage("请阅读并同意我们的隐私政策。")
        builder.setPositiveButton("同意") { dialog, _ ->
            dialog.dismiss()
            updatePrivacyCompliance()
        }
        builder.setNegativeButton("拒绝") { dialog, _ ->
            dialog.dismiss()
            Toast.makeText(this, "请同意隐私政策以使用地图功能", Toast.LENGTH_LONG).show()
            finish()  // 关闭应用
        }
        builder.setCancelable(false)
        builder.show()
    }

    // 更新隐私合规
    private fun updatePrivacyCompliance() {
        try {
            // 设置隐私权政策弹窗告知用户 (新版本需要三个参数)
            AMapLocationClient.updatePrivacyShow(applicationContext, true, true)
            // 设置用户已经同意隐私权政策
            AMapLocationClient.updatePrivacyAgree(applicationContext, true)
        } catch (e: Exception) {
            e.printStackTrace()
            Toast.makeText(this, "隐私合规设置失败：${e.message}", Toast.LENGTH_LONG).show()
            finish()  // 关闭应用
            return
        }

        // 初始化地图和定位
        initMap()
        initLocation()
    }

    // 初始化地图
    private fun initMap() {
        aMap = mMapView.map  // 获取地图对象

        // 配置地图UI
        aMap.uiSettings.isZoomControlsEnabled = true  // 显示缩放按钮
        aMap.uiSettings.isMyLocationButtonEnabled = true  // 显示定位按钮
        aMap.uiSettings.isCompassEnabled = true  // 显示指南针
        aMap.uiSettings.isScaleControlsEnabled = true  // 显示比例尺

        // 配置"我的位置"显示样式
        myLocationStyle = MyLocationStyle()
        myLocationStyle.showMyLocation(true)  // 显示定位点
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_FOLLOW)  // 定位点跟随设备旋转


        aMap.isMyLocationEnabled = true  // 开启定位图层
    }

    // 初始化定位
    private fun initLocation() {
        // 初始化定位客户端
        mLocationClient = AMapLocationClient(applicationContext)
        // 设置定位回调监听
        mLocationClient?.setLocationListener(this)

        // 配置定位参数
        mLocationOption = AMapLocationClientOption()
        mLocationOption?.apply {
            locationMode = AMapLocationClientOption.AMapLocationMode.Hight_Accuracy  // 高精度模式
            interval = 2000  // 定位间隔（毫秒）
            isOnceLocationLatest = true  // 获取最近3s内精度最高的一次定位结果
            isNeedAddress = true  // 返回地址信息
        }
        mLocationClient?.setLocationOption(mLocationOption)

        // 开始定位
        mLocationClient?.startLocation()
    }

    // 定位结果回调
    override fun onLocationChanged(location: AMapLocation?) {
        location?.let {
            if (it.errorCode == 0) {
                // 定位成功
                val address = it.address  // 详细地址
                val city = it.city  // 城市
                val latitude = it.latitude  // 纬度
                val longitude = it.longitude  // 经度

                // 显示定位信息
                Toast.makeText(
                    this,
                    "当前位置：$city $address\n经纬度：$latitude, $longitude",
                    Toast.LENGTH_LONG
                ).show()

                // 将地图中心移动到当前位置
                aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
                    LatLng(latitude, longitude),
                    15f  // 缩放级别（3-20，数值越大越详细）
                ))

                // 添加标记点
                addMarker(LatLng(latitude, longitude), "我的位置", address)
            } else {
                // 定位失败
                Toast.makeText(
                    this,
                    "定位失败：${it.errorInfo}（错误码：${it.errorCode}）",
                    Toast.LENGTH_LONG
                ).show()
            }
        }
    }

    // 添加标记点
    private fun addMarker(position: LatLng, title: String, snippet: String) {
        val markerOptions = MarkerOptions()
        markerOptions.position(position)
        markerOptions.title(title)
        markerOptions.snippet(snippet)
        markerOptions.draggable(false)  // 不可拖动
        aMap.addMarker(markerOptions)
    }

    // 权限请求结果回调
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == PERMISSION_REQUEST_CODE) {
            val allGranted = grantResults.all { it == PackageManager.PERMISSION_GRANTED }
            if (allGranted) {
                // 权限已获取，更新隐私合规并初始化地图和定位
                updatePrivacyCompliance()
            } else {
                Toast.makeText(this, "请授予必要权限以使用地图功能", Toast.LENGTH_LONG).show()
                finish()  // 权限不足，关闭应用
            }
        }
    }

    // 地图生命周期管理
    override fun onResume() {
        super.onResume()
        mMapView.onResume()
    }

    override fun onPause() {
        super.onPause()
        mMapView.onPause()
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        mMapView.onSaveInstanceState(outState)
    }

    override fun onDestroy() {
        super.onDestroy()
        mMapView.onDestroy()
        // 停止定位并释放资源
        mLocationClient?.stopLocation()
        mLocationClient?.onDestroy()
    }
}